package cn.tedu.springboot.security.config;

import cn.tedu.springboot.security.filter.JwtAuthorizationFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author BJ
 * @date 2022/10/22 14:36
 * Security 配置类
 */
@Slf4j
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    public SecurityConfiguration(){
        log.debug("加载配置类：SecurityConfiguration");
    }

    @Autowired
    JwtAuthorizationFilter jwtAuthorizationFilter;

    //配置密码编码器(将用于登录的密码编码),此对象 Security 加载时会自动调用
    @Bean
    public PasswordEncoder passwordEncoder(){
        log.debug("创建了@bean方法创建的对象:passwordEncoder");
        return new BCryptPasswordEncoder();
    }

    // 用于在在service实现类中验证用户
    @Bean
    @Override
    public AuthenticationManager authenticationManager() throws Exception {
        log.debug("创建@Bean方法定义的对象：AuthenticationManager");
        return super.authenticationManager();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 配置白名单
        String[] urls = {
                "/doc.html",
                "/**/*.js",
                "/**/*.css",
                "/swagger-resources",
                "/v2/api-docs",
                "/admins/login"
        };

        http.csrf().disable(); // 禁用CSRF（防止伪造的跨域攻击）
        http.cors();  // 启用Spring Security框架的处理跨域的过滤器，此过滤器将放行跨域请求，包括预检的OPTIONS请求

        http.authorizeRequests() // 对请求执行认证与授权
                .antMatchers(urls) // 匹配某些请求路径
                .permitAll() // （对此前匹配的请求路径）不需要通过认证即允许访问
                .anyRequest() // 除以上配置过的请求路径以外的所有请求路径
                .authenticated(); // 要求是已经通过认证的

//        http.formLogin(); // 开启表单验证，即视为未通过认证时，将重定向到登录表单，如果无此配置，则直接响应403
        http.addFilterBefore(jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
